<template>
  <view class="todoDetail">
    <u-form :model="form" :rules="rules" ref="uFormRef">
      <u-form-item label="标题" prop="title">
        <u-input
          v-model="form.title"
          placeholder="请输入标题"
          :disabled="mode === 'view'"
        ></u-input>
      </u-form-item>
      <u-form-item label="内容" prop="content">
        <u-input
          v-model="form.content"
          type="textarea"
          maxlength="500"
          placeholder="请输入内容"
          :disabled="mode === 'view'"
        ></u-input>
      </u-form-item>
      <u-form-item label="分类" prop="classification_id"
        ><u-input
          placeholder="请选择分类"
          v-model="classificationSelect.current.label"
          type="select"
          @click="classificationSelect.show = true"
      /></u-form-item>
      <u-form-item label="备注" prop="remark" v-if="mode === 'add'">
        <u-input
          v-model="form.remark"
          type="textarea"
          maxlength="500"
          placeholder="请输入备注"
        ></u-input>
      </u-form-item>
      <u-button
        v-if="mode !== 'view'"
        type="primary"
        @click="submit"
        :loading="submitLoading"
        >提交</u-button
      >
    </u-form>
    <DfbPopSelect
      v-model:show="classificationSelect.show"
      :list="classificationSelect.list"
      :defaultValue="classificationSelect.current.value"
      @confirm="selectTagConfirm"
    ></DfbPopSelect>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { onLoad, onReady } from "@dcloudio/uni-app";
import DfbPopSelect from "@/components/dfb-pop-select/index.vue";

const mode = ref("add"); // add/edit/view
const uFormRef = ref(null);
const form = reactive({
  title: "",
  content: "",
  classification_id: "",
  remark: "[创建待办]",
});

const rules = {
  title: [
    { required: true, message: "请输入标题", trigger: ["blur"] },
    { max: 30, message: "标题长度不能超过30个字符", trigger: ["blur"] },
  ],
  content: [
    { max: 500, message: "内容长度不能超过500个字符", trigger: ["blur"] },
  ],
  classification_id: [
    { required: true, message: "请选择分类", trigger: ["blur"] },
  ],
  remark: [
    { max: 500, message: "备注长度不能超过500个字符", trigger: ["blur"] },
  ],
};

onReady(() => {
  uFormRef.value.setRules(rules);
});

const classificationSelect = reactive({
  show: false,
  current: { label: "", value: "" },
  list: [],
});

const selectTagConfirm = (selectedData) => {
  classificationSelect.current = selectedData;
  form.classification_id = selectedData.value;
};

const getTodoDetail = async (id) => {
  const res = await vk.callFunction({
    url: "client/todo/kh/getTodoDetail",
    data: { _id: id },
  });
  Object.assign(form, res.data);
  setDefaultCurrent();
};

const getClassificationList = () => {
  // const res = await uni.vk.callFunction({
  //   url: "client/classification/kh/getClassificationList",
  //   data: { type: "todo" },
  // });
  // res.data.forEach((item) => {
  //   item.label = item.name;
  //   item.value = item._id;
  // });
  // classificationSelect.list = res.data;
  const store = uni.vk.getVuexStore();
  const res = store.getters["baseData/todo"];
  classificationSelect.list = [
    ...classificationSelect.list,
    ...res.map((item) => ({ label: item.name, value: item._id })),
  ];
};

const setDefaultCurrent = () => {
  if (classificationSelect.list.length === 0 || !form.classification_id) return;
  classificationSelect.current = classificationSelect.list.find((item) => {
    return form.classification_id === item.value;
  });
};

onLoad(async (options) => {
  getClassificationList();
  if (options.id) {
    mode.value = options.mode === "edit" ? "edit" : "view";
    uni.setNavigationBarTitle({
      title: options.mode === "edit" ? "编辑待办" : "查看待办",
    });
    // 加载待办数据
    getTodoDetail(options.id);
  } else {
    mode.value = "add";
    uni.setNavigationBarTitle({
      title: "新增待办",
    });
    if (options.classification_id) {
      form.classification_id = options.classification_id;
      setDefaultCurrent();
    }
  }
});

const submitLoading = ref(false); // 提交按钮的loading状态
const submit = () => {
  uFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        if (mode.value === "add") {
          const res = await vk.callFunction({
            url: "client/todo/kh/addTodo",
            data: {
              title: form.title,
              content: form.content,
              classification_id: form.classification_id,
              remark: form.remark,
            },
          });
          submitLoading.value = false;
          vk.toast(res.msg);
          vk.navigateBack();
          uni.$emit("refreshTodoList");
          uni.$emit("refreshTodoDetail");
        } else {
          const res = await vk.callFunction({
            url: "client/todo/kh/editTodo",
            data: {
              _id: form._id,
              title: form.title,
              content: form.content,
              classification_id: form.classification_id,
            },
          });
          submitLoading.value = false;
          vk.toast(res.msg);
          vk.navigateBack();
          uni.$emit("refreshTodoList");
          uni.$emit("refreshTodoDetail");
        }
      } catch (e) {
        submitLoading.value = false;
      }
    }
  });
};
</script>

<style scoped lang="scss">
.todoDetail {
  padding: 10px;
  .u-btn {
    margin-top: 30px;
  }
  :deep(.tagInput) {
    width: 100%;
    // background: pink;
    min-height: 2.1875rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 10px;
    .tagArea {
      flex: 1;
      .u-tag {
        margin: 0 5px;
      }
    }
  }
  :deep(.u-input__textarea) {
    min-height: unset !important;
  }
}
</style>
